# -*- coding:utf-8 -*-
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import tkinter.messagebox
import tkinter as tk
from tkinter import filedialog
from media import basic
import os
import subprocess
import re
from media import mediaUtil
import threading
'''
从视频中提取音频文件
'''
class vnFarame(object):
    def __init__(self,parent):
        self.root = tkinter.Toplevel(parent)
        self.root.title('音频提取')
         #子窗口随着主窗口关闭或最小化
        self.root.transient(parent)
        self.root.resizable(False, False)
        self.root.minsize(500, 155)
        self.centerWin(self.root,500, 155)
        
        vnFrame = ttk.Frame(self.root)
        bm = PhotoImage(file = mediaUtil.SOURCE_PATH+'mp3.png')
        tipLabel = Label(vnFrame,image=bm)
        tipLabel.bm = bm
        tipLabel.grid(row=0,rowspan=6,column=0,padx=5,pady=5,sticky=(N, W, E, S))
        
        audioLabel = Label(vnFrame,text='视频文件：')
        audioLabel.grid(column=1, row=2,padx=3,sticky=(N, W, E, S))
        self.videoString = StringVar()
        self.videoPath = Entry(vnFrame,textvariable = self.videoString,width=30,state=DISABLED)
        self.videoPath.grid(column=2, row=2,padx=3,sticky=(W, E))
        videoPathBtn = ttk.Button(vnFrame,text="选择文件",width=10,command=self.getVideoPath).grid(row=2,column=3,sticky=W+E,padx=10)
        
        outLabel = Label(vnFrame,text='存放文件夹：')
        outLabel.grid(column=1, row=3,padx=3,sticky=(N, W, E, S))
        self.audioString = StringVar()
        self.audioPath = Entry(vnFrame,textvariable = self.audioString,width=30,state=DISABLED)
        self.audioPath.grid(column=2, row=3,padx=3,sticky=(W, E))
        audioPathBtn = ttk.Button(vnFrame,text="选择文件夹",width=10,command=self.getAudioPath).grid(row=3,column=3,sticky=W+E,padx=10)

        self.execBtn = ttk.Button(vnFrame,text="提取",width=10,command=self.getVideoVn)
        self.execBtn.grid(row=7,column=3,sticky=W+E,padx=10)
        
        vnFrame.grid(row=0,column=0,pady=5,sticky=(N, W, E, S))
        self.statusLabel = Label(vnFrame,text='已就绪',relief=GROOVE,anchor=W)
        self.statusLabel.grid(row=8,column=0,columnspan=4,pady=5,sticky=(N, W, E, S))
        
    '''窗口居中'''
    def centerWin(self,root,width,height):
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2)  
        root.geometry(size)
        
    '''获取视频文件地址'''
    def getVideoPath(self):
        self.videoString.set('')
        path = filedialog.askopenfilename()
        if path !="":
            ext = os.path.splitext(path)[1][1:]
            isVideo = 0
            for et in basic.VIDEOS:
                if et == ext:
                    isVideo = 1
            if isVideo == 1:
                self.videoString.set(path)
            else:
                tkinter.messagebox.showerror("提示","请选择视频文件")
        
    '''获取音频提取的存放路径'''
    def getAudioPath(self):
        path = filedialog.askdirectory()
        if path !="":
            self.audioString.set(path)
    
    '''提取视频中的音频'''
    def getVideoVn(self):
        try:
            videoPath = self.videoString.get()
            if videoPath == "":
                tkinter.messagebox.showerror("提示","请选择视频文件")
                return False
            audioPath = self.audioString.get()
            if audioPath =="":
                tkinter.messagebox.showerror("提示","请选择存放文件夹")
                return False
            self.statusLabel['text']='提取中'
            videoName = os.path.basename(videoPath)
            ret = list(re.finditer('\.', videoName))
            videoName = videoName[0:ret[-1].span()[0]]
            outputFile = audioPath+'/{0}'.format(videoName)
            #获取提交音频命令
            cmd = mediaUtil.cmd_getVideoVn(videoPath, outputFile)
            if cmd == None:
                tkinter.messagebox.showerror("提示","无法获取音频提取命令")
                return Flase
            #执行提取音频命令
            subprocess.Popen(cmd)
            #禁用提取按钮
            self.execBtn.config(state=DISABLED)
            #获取提取进度
            vn_thread = threading.Thread(target=self.getVnProgress,args=(None,cmd))
            vn_thread.start()
        except:
            self.statusLabel['text']='提取失败'
    
    '''获取提取进度'''
    def getVnProgress(self,x,cmd):
        try:
            iscomplete = 0
            while iscomplete ==0:
                info = mediaUtil.getCmdExecInfo(cmd)
                if info !="":
                    iscomplete=1
            if iscomplete ==1:
                self.statusLabel['text']='提取成功'
            #启用提取按钮
            self.execBtn.config(state=NORMAL)
        except:
            self.statusLabel['text']='提取失败'
        